<template>
    <!-- 操作按钮区 -->
   <div class="action-buttons">
     <el-button type="primary" @click="Export">导出</el-button>
      
   </div>
   
   <div>

       <div class="page-title">
       <h2>到货质检明细表</h2>
       </div>
       <!-- 生产计划列表（仅展示序号列相关结构） -->
       <div class="table-container">
            <el-table :data="planList" style="width: 100%">
               <el-table-column type="selection" width="55"></el-table-column>
               <el-table-column type="index" label="序号" width="50"></el-table-column>
               <el-table-column prop="itemCode" label="物品编码"></el-table-column>
               <el-table-column prop="itemName" label="物品名称"></el-table-column>
               <el-table-column prop="specificationModel" label="规格型号"></el-table-column>
               <el-table-column prop="unit" label="单位"></el-table-column>
               <el-table-column prop="brand" label=" 品牌"></el-table-column>
               <el-table-column prop="purchaseQuantity" label="采购数量"></el-table-column>
               <el-table-column prop="inspectionType" label="检验类型"></el-table-column>
               <el-table-column prop="receivedQuantity" label="收货数量"></el-table-column>
               <el-table-column prop="inspectionQuantity" label="检验数量"></el-table-column>
               <el-table-column prop="qualifiedquantity" label="合格数量"></el-table-column>
               <el-table-column prop="inboundQuantity" label="可入库数量"></el-table-column>
               <el-table-column prop="returnQuantity" label=" 退货数量"></el-table-column>
               <el-table-column prop="remarks" label="备注"></el-table-column>
                  <!-- <el-table-column prop="right" label="操作">
                   <template #default="scope">
                       <el-button type="text" @click="GetBYIdProductionPlanning(scope.row.basicInfoid)">编辑</el-button>
                       <el-button  type="text" @click="DeleteProductionPlanning(scope.row.basicInfoid)">删除</el-button>
                   </template>
               </el-table-column> -->
           </el-table>
          <!-- 分页部分
            <el-button @click="batchDelete">批量删除</el-button> -->
       </div>
        <div style="margin-top: 20px">
           <el-pagination
               v-model:current-page="page.pageindex"
               v-model:page-size="page.pageSize"
               :page-sizes="[5, 20, 25, 30]"
               :background="true"
               prev-text="上一页"
               next-text="下一页"
               layout="total, sizes, prev, pager, next, jumper"
               :total="total.totalCount"
               @size-change="handleSizeChange"
               @current-change="handleCurrentChange"
           />
       </div>
   </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { Materialread, Materialwrite } from '@/axios/axiosHelper';
import { ElMessage, ElMessageBox } from 'element-plus';
import router from '@/router';
import axios from 'axios';


// 定义搜索表单数据
const prolist = ref({
    InspectionSubject:'',
    InspectionOrderNumber:'',
    InspectionDate:'',
    PurchaseOrderNumber:'',
    PurchaseDate:'',
    SupplierName:'',
});

// 定义分页总数
const total = ref({
 totalCount: 0,
 pageCount:0,
});
// 定义分页对象
const page = ref({
   pageindex: 1,
   pageSize: 5,
});

// 模拟生产计划列表数据
const planList = ref([
   {
    "purchaseInfoid": '',
        "itemCode": "",
        "itemName": "",
        "specificationModel": "",
        "unit": "",
        "brand": "",
        "purchaseQuantity": '',
        "inspectionType": "",
        "receivedQuantity": '',
        "inspectionQuantity": '',
        "qualifiedquantity": '',
        "inboundQuantity": '',
        "returnQuantity": '',
        "remarks": " ",
        "basicInfoid": '',
        "isDel": false
   } 
]);
const formatDate = (dateStr) => {
 const date = new Date(dateStr);
 const year = date.getFullYear();
 const month = String(date.getMonth() + 1).padStart(2, '0');
 const day = String(date.getDate()).padStart(2, '0');
 const hour = String(date.getHours()).padStart(2, '0');
 const minute = String(date.getMinutes()).padStart(2, '0');
 const second = String(date.getSeconds()).padStart(2, '0');
 return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
};


// 日期格式化过滤器
const dateFormatter = (date) => {
 if (date) {
   return date.toISOString().split('T')[0]
 }
 return ''
}
// 表格引用
const tableRef = ref(null);

// 全选状态
const allChecked = ref(false);


const ShowMaterials = () => {
//  console.log("ShowMaterials");
   Materialread.get("f-read/api/Arrival/GetPurchaseInfo", {
       params: {
           pageindex: page.value.pageindex,
           pageSize: page.value.pageSize,
           InspectionSubject: prolist.value.InspectionSubject,
           InspectionOrderNumber: prolist.value.InspectionOrderNumber,
           InspectionDate: prolist.value.InspectionDate,
           PurchaseOrderNumber: prolist.value.PurchaseOrderNumber,
           PurchaseDate: prolist.value.PurchaseDate,
           SupplierName: prolist.value.SupplierName,
       }
   }).then((res) => {
       planList.value = res.data.data.list;
       console.log("显示补料数据",planList.value);

       total.value.totalCount = res.data.data.totalCount;
       total.value.pageCount = res.data.data.pageCount;
       // 重置全选状态和选中的 ID 列表
       allChecked.value = false;
       checkedIds.value = [];
   }).catch((error) => {
       console.error('接口请求失败:', error);
       ElMessage.error('数据获取失败，请稍后重试');
   });
};



// 编辑跳转修改
const GetBYIdProductionPlanning = (basicInfoid) => {
   router.push({
       name: 'UpdateArrival',
       query: {
        basicInfoid: basicInfoid
       }
   });
   console.log(basicInfoid);
};

//跳转添加
const batchSaveDetails = () => {
    router.push({
       name: 'AddFeeding',
       
   });
   // console.log(feedingId);
}
// 导入
// const handleImport = () => {
 
//   Materialread.get("/l-read/api/GetValues/ExportToExcel").then((res)=>{
//     ElMessage.success('导入成功');
//   })
// };


// 删除单条记录
const DeleteProductionPlanning = async (basicInfoid) => {
   try {
       const confirmResult = await ElMessageBox.confirm(
           '确认删除该条记录？',
           '提示',
           {
               confirmButtonText: '确定',
               cancelButtonText: '取消',
               type: 'warning'
           }
       );
       if (confirmResult === 'confirm') {
           const response = await axios.post(
               `https://localhost:7229/api/Arrival/DelBasicInfo`,
               {
                   params: { BasicInfoid: basicInfoid.toString() }
               }
           );
           if (response.data.code === 300) {
               ElMessage.success('删除成功');
               ShowMaterials(); // 调用 ShowMaterials 方法刷新数据
           } else {
               ElMessage.error(`删除失败：${response.data.message}`);
           }
       }
   } catch (error) {
       if (error !== 'cancel') {
           console.error('删除错误:', error);
           ElMessage.error('删除失败，请检查网络或联系管理员');
       }
   }
};
// 选中的 ID 列表
const checkedIds = ref([]);

// 处理全选
const handleCheckAllChange = (value) => {
   if (value) {
       checkedIds.value = planList.value.map(item => item.feedingId);
   } else {
       checkedIds.value = [];
   }
   allChecked.value = value;
};

// // 批量删除
// const batchDelete = async () => {
//     if (checkedIds.value.length === 0) {
//         ElMessage.warning('请选择要删除的记录');
//         return;
//     }
//     try {
//         const confirmResult = await ElMessageBox.confirm(
//             '确认删除选中的记录？',
//             '提示',
//             {
//                 confirmButtonText: '确定',
//                 cancelButtonText: '取消',
//                 type: 'warning'
//             }
//         );
//         if (confirmResult === 'confirm') {
//             const ids = checkedIds.value.join(',');
//             const response = await Materialwrite.post(
//                 `/l-write/api/Ment/DelFeeding`,
//                 {
//                     bomid: ids
//                 }
//             );
//             if (response.data.code === 300) {
//                 ElMessage.success('批量删除成功');
//                 ShowMaterials();
//             } else {
//                 ElMessage.error(`批量删除失败：${response.data.message}`);
//             }
//         }
//     } catch (error) {
//         if (error !== 'cancel') {
//             console.error('批量删除错误:', error);
//             ElMessage.error('批量删除失败，请检查网络或联系管理员');
//         }
//     }
// };

const handleSizeChange = (val) => {
   page.value.PageSize = val;
   ShowMaterials();
};
const handleCurrentChange = (val) => {
   page.value.PageIndex = val;
   ShowMaterials();
};
onMounted(() => {
   ShowMaterials();
})
</script>

<style scoped>
.search-section {
   margin-bottom: 20px;
}

.table-container {
   max-height: 400px; /* 固定表格最大高度 */
   overflow-y: auto; /* 超出高度显示滚动条 */
   margin-bottom: 20px; /* 为分页预留空间 */
}

.el-table {
   width: 100%; /* 表格宽度占满容器 */
}
</style>
   
